<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { type EChartsOption } from 'echarts'
import type { AnnualSalesVehicle, SaleInfoParam } from '@/api/dashboard/types'
import { getAnnualSalesOfVehicles } from '@/api/dashboard/dashboard'
import { useResponsiveLineForVehicles } from '@/h5/useEchartsOption/useEchartsOption'
import '@/h5/analysis.css'

const props = defineProps<{ yearId: number; customerId?: number }>()

const loading = ref(false)
const chartData = reactive<AnnualSalesVehicle[]>([
  { name: 'A00', value: 0 },
  { name: 'A0', value: 0 },
  { name: 'A', value: 0 },
  { name: 'B', value: 0 },
  { name: 'C', value: 0 },
  { name: 'D', value: 0 },
  { name: 'SUV', value: 0 },
  { name: 'MPV', value: 0 },
  { name: '跑车', value: 0 },
])

const formModel = reactive<SaleInfoParam>({
  yearId: props.yearId ?? 2024,
  customerId: props.customerId ?? 0,
})

function setChartData(data: AnnualSalesVehicle[]) {
  chartData.splice(0, chartData.length, ...data)
}

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    console.log('年度销售车辆组件 - 开始调用 API，参数:', { 
      customerId: props.customerId, 
      yearId: props.yearId 
    })
    const res = await getAnnualSalesOfVehicles({ 
      customerId: props.customerId,
      yearId: props.yearId 
    })
    console.log('年度销售车辆组件 - API 调用成功，返回数据:', res)
    setChartData(res?.data || [])
  }
  catch (error) {
    console.error('年度销售车辆组件 - API 调用失败:', error)
  }
  finally {
    loading.value = false
  }
}

watch(() => [props.yearId, props.customerId], ([y, c]) => {
  formModel.yearId = y ?? 2024
  formModel.customerId = c ?? 0
  init()
})

onMounted(() => {
  init()
})

const option = computed<EChartsOption>(() => {
  return useResponsiveLineForVehicles(chartData)
})

const isEmpty = computed(() => {
  // 放宽空数据判断：只在没有任何数据项时显示空提示
  return !chartData.length
})
</script>

<template>
  <div class="h5-analysis-block">
    <div class="chart-title">年度销售车辆级别统计</div>
    <div class="chart-container">
      <template v-if="!isEmpty">
        <Chart :option="option" :loading="loading" height="auto" />
      </template>
      <template v-else>
        <div class="chart-empty">
          <a-empty description="暂无数据" />
        </div>
      </template>
    </div>
  </div>
</template>

<!-- 移除局部样式，使用全局 analysis.css -->